import React, { useEffect, useState } from 'react';
import { createStyles } from 'antd-style';
import { Spin, Image as ImageAntd, ImageProps } from "antd";

interface ProImageLoaderProps extends React.DetailedHTMLProps<React.ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement> {
  url: string,
  imageProps?: ImageProps,
}

export const ProImageLoader: React.FC<ProImageLoaderProps> = ({ url, className = "", imageProps, ...restProps }) => {
  const { styles } = useStyle();
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadImageAsync(url).then(() => {
      setLoading(false);
    }).catch(() => {
      setLoading(false);
    });
  }, [url]);

  return <div className={`${styles.proImageLoader} ${className}`}>
    {loading ? <Spin /> : <ImageAntd width={"100%"} height={"100%"} src={url} preview={false} {...imageProps} {...restProps} />}
  </div>
}

const loadImageAsync = (url: string) => {
  return new Promise(function (resolve, reject) {
    const image = new Image();
    image.onload = () => {
      resolve(url);
    };
    image.onerror = (e) => {
      // console.error('图片载入失败')
      reject(e)
    };
    image.src = url;
  });
}

const useStyle = createStyles(({ css }) => ({
  proImageLoader: css`
    /* width: 100%; */
    /* height: 100%; */
    display: flex;
    align-items: center;
    justify-content: center;
    
    img{
      width: 100%;
      height: 100%;
    }
  `
}))
